<template>
  <div class="page">
    <div class="page-background">
      <div class="back">
        <div class="header">
          <div class="head-center">
            <span class="close-btn" @click="close">
              <var-icon name="chevron-left" />
            </span>
            <span class="title">今日打卡</span>
          </div>
        </div>
      </div>
    </div>
    <div class="container">
      <div class="center">
        <div class="item">
          <div class="item-container">
            <span class="label iconfont" style="width:24px;hegiht:24px">
              <img src="@/assets/datepicker.png" alt srcset />
            </span>
            <span class="text">{{ today.replace(/-/g, ".") }}</span>
          </div>
        </div>
        <!-- 选择打卡的课程 -->
        <div class="item">
          <div class="select-class">
            <div class="select-title">选择课程：{{ form.className }}</div>
            <div class="select-center">
              <div v-for="(item, index) in state.list" :key="index"
                :class="state.active === index ? 'select-item active' : 'select-item'" @click="onChange(index)">
                <div class="select-item-container" style>
                  <div class="img">
                    <img :src="item.imgUrl || defaultClassImg" alt srcset />
                  </div>
                  <div class="select-title">
                    {{ item.className }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 打卡地点（选择图书馆 -->
        <div class="item" @click="bottom = true">
          <div class="item-container">
            <span class="label iconfont" style="width:24px;hegiht:24px">
              <img src="@/assets/address.png" alt srcset />
            </span>
            <span class="text">{{ form.addressName }}</span>
          </div>
        </div>
        <var-popup @click-overlay="bottom = false" position="bottom" :show="bottom">
          <van-picker title="标题" :columns="state.libraryList" @confirm="onConfirmAddress" v-model="addressValue" />
        </var-popup>




        <!-- 开始时间和结束时间 -->
        <div class="item" @click="handleOpenTimeSelect">
          <div class="item-container">
            <span class="iconfont label">
              开始时间：
            </span>
            <span class="text">{{ form.startTime || null }}</span>
          </div>
        </div>
        <van-popup v-model:show="show" position="bottom" :style="{ height: '50%' }">
          <SelectDateTimeComponent title="日期时间" @setShow="setShow" @onOk="onConfirmStartTime" />
        </van-popup>


        <div class="item" @click="openSelectEndTime">
          <div class="item-container" style="border-bottom:none">
            <span class="iconfont label">结束时间：</span>
            <span class="text">{{ form.endTime || null }}</span>
          </div>
        </div>
        <van-popup v-model:show="show1" position="bottom" :style="{ height: '50%' }">
          <SelectDateTimeComponent title="日期时间" @onCancel="setShow1" @onOk="onConfirmEndTime" />
        </van-popup>
        <var-loading :loading="loading">
          <div class="addBtn" @click="onClickAddRecord">
            <div class="addBtn-container">添加</div>
          </div>
        </var-loading>
      </div>
    </div>
  </div>
</template>

<script>
import { getAddressList, getClassList, addSign } from "@/api";
import { reactive, ref, onMounted } from "vue";
import { useStore } from "vuex";

import { concatInt, getNowTime } from "@/util/formTime";
import defaultImg from "@/assets/book.png";

import SelectDateTimeComponent from "@/components/vant-pick-group/index.vue"
import dayjs from "dayjs";
export default {
  name: "AddRecordView",
  emits: ["setShowAdd"],
  components: {
    SelectDateTimeComponent
  },
  setup(props, ctx) {
    const addressValue = ref([]); //用以选择地址双向绑定
    const show = ref(false);
    const show1 = ref(false);
    const loading = ref(false);
    const setLoading = Boolean => {
      loading.value = Boolean;
    };
    const store = useStore();
    const defaultClassImg = defaultImg;
    const today = getNowTime("YYYY-MM-DD");

    const handleOpenTimeSelect = () => {
      show.value = true
    };
    const openSelectEndTime = () => {
      show1.value = true
    };

    // form表单
    const form = reactive({
      createDate: getNowTime("YYYY-MM-DD HH:mm:ss"),
      userId: store.state.userInfo.userId,
      userName: store.state.userInfo.userName,
      userPhone: store.state.userInfo.userPhone,
      classId: "",
      className: "",
      startTime: dayjs().format("YYYY/MM/DD HH:mm"),
      endTime: dayjs().add(2, 'h').format("YYYY/MM/DD HH:mm"),
      addressName: "",
      addressId: '',

    });
    // 设置form表单的函数
    const setForm = params => {
      const { key, val } = params;
      form[key] = val;
    };
    const bottom = ref(false);
    const state = reactive({
      active: 0,
      list: [],
      libraryList: [[]]
    });
    const close = () => {
      ctx.emit("getTimeMonth");
      ctx.emit("getTimeYear");
      ctx.emit("setShowAdd");
    };

    // 变更选课
    const onChange = active => {
      state.active = active;
      const obj = state.list[active];
      form.classId = obj._id;
      form.className = obj.className;
    };

    // 打开选图书馆的select
    const openSelectLibrary = (text, index) => {
      bottom.value = false;
    };

    // 控制弹框显示与否
    const setShow = (value = false) => {
      show.value = value
    }
    const setShow1 = (value = false) => {
      show1.value = value
    }

    // 选择开始时间
    const onConfirmStartTime = (object) => {
      const { value } = object
      setForm({ key: "startTime", val: value })
      setShow(false)
    }
    // 选择结束时间
    const onConfirmEndTime = (object) => {
      const { value } = object
      setForm({ key: "endTime", val: value })
      setShow1(false)
    }

    // 选择地点
    const onConfirmAddress = ({ selectedOptions }) => {
      console.log("选择的地点：\n", selectedOptions[0].text, selectedOptions[0].value)
      form.addressName = selectedOptions[0].text
      form.addressId = selectedOptions[0].value
    }

    // 添加打卡事件
    const onClickAddRecord = () => {
      let param = {
        ...form,
        startTime: dayjs(form.startTime).valueOf(),
        endTime: dayjs(form.endTime).valueOf(),
      }
      console.log("参数配置：\n", param)
      setLoading(true);
      addSign({
        url: "/asign-api/creteAsign",
        params: {
          ...param
        },
        success: res => {
          console.log("创建成功", res);
          close();
        },
        fail: error => { },
        complete: () => setLoading(false)
      });
    };

    // 获取地点列表
    const getAdress = () => {
      getAddressList({
        params: {
          userId: store.state.userInfo.userId,
        },
        success: data => {
          const { list = [] } = data;
          let array = [];
          list.forEach(item => {
            console.log(item)
            array.push({
              text: item.addressName,
              value: item._id
            })
          })
          console.log(array)
          if (array.length > 0) {
            // 赋值默认值
            addressValue.value = [array[0].value]
          }
          state.libraryList = [...array]
        },
        error: error => { },
        complete: () => { }
      });
    };

    //获取选课列表
    const getClass = () => {
      getClassList({
        params: {
          userId: store.state.userInfo.userId,
        },
        success: data => {
          const { list = [] } = data;
          state.list = [...list];
          if (list.length === 0) {
            // 您尚未添加课程，请先添加课程
          } else {
            // 给form赋值个初始值
            const { _id, className } = list[0];
            form.classId = _id;
            form.className = className;
          }
        },
        error: error => { },
        complete: () => { }
      });
    };

    onMounted(() => {
      getAdress();
      getClass();
    });

    return {
      show,
      show1,
      loading,
      defaultClassImg, //导出默认图片
      today,
      form,
      // timeSelectRef1,
      // timeSelectRef2,
      handleOpenTimeSelect,
      openSelectEndTime,
      bottom,
      close,
      state,
      onChange,
      openSelectLibrary,
      onClickAddRecord,
      setForm,
      addressValue,
      onConfirmStartTime,
      onConfirmEndTime,
      setShow,
      setShow1,
      onConfirmAddress
    };
  }
};
</script>

<style lang="scss" scoped>
.var-popup--bottom {
  height: 40%;

  .popup-example-block {
    padding: 20px 24px;
  }
}

.page {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  padding: 10px;
  background-color: rgb(254, 250, 238);

  .page-background {
    z-index: -1;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;

    .back {
      height: 200px;
      width: 100%;
      border-radius: 0 0 25px 25px;
      background-color: rgb(97, 99, 234);
      overflow: hidden;

      .header {
        width: 100%;
        height: 100%;

        // background-color: orange;
        .head-center {
          width: 100%;
          padding: 30px;
          position: relative;

          .close-btn {
            position: absolute;
            color: white;
            display: inline-block;
            border-radius: 50px;
            background-color: rgba(245, 245, 245, 0.365);
            width: 30px;
            height: 30px;
            display: flex;
            justify-content: center;
            align-items: center;
          }

          .title {
            z-index: -1;
            width: 100%;
            line-height: 30px;
            display: inline-block;
            text-align: center;
            color: white;
            font-weight: 600;
          }
        }
      }
    }
  }

  .container {
    width: 100%;
    height: 100%;
    color: rgb(43, 43, 43);
    // padding: 20px;
    margin-top: 80px;
    font-size: 12px;

    .center {
      background-color: white;
      // height: 100%;
      padding: 10px;
      border-radius: 15px;

      .item {
        width: 100%;
        padding: 5px;

        .item-container {
          padding: 3px 0;
          border-bottom: 1px solid rgb(255, 191, 184);
          line-height: 24px;
          display: flex;
          align-items: center;

          .iconfont {
            display: inline-block;
            width: 24px;
            height: 24px;
            margin-right: 10px;

            img {
              width: 100%;
              height: 100%;
            }
          }

          .label {
            margin-right: 10px;
            font-size: 12px;
            width: auto;
          }

          .text {
            display: inline-block;
            height: 24px;
            line-height: 24px;
          }
        }

        .select-class {
          padding: 3px 0;
          border-bottom: 1px solid rgb(255, 191, 184);

          .select-title {
            display: flex;
            justify-content: start;
          }

          .select-center::-webkit-scrollbar {
            width: none;
            height: none;
          }

          .select-center {
            display: flex;
            overflow-y: auto;

            .select-item {
              width: 70px;
              // height: 70px;
              padding: 4px 4px;

              .select-item-container {
                width: 100%;
                height: 100%;
                width: 62px;
                height: 78px;
                display: flex;
                flex-direction: column;
                padding: 2px;

                .img {
                  width: 100%;
                  flex: 1;
                  overflow: hidden;

                  img {
                    width: 100%;
                    height: 100%;
                  }
                }

                .select-title {
                  width: 100%;
                }
              }
            }

            .active {
              .select-item-container {
                background-color: #ffbfb8;
                color: white;

                .img {
                  // border: 2px solid rgba(105, 105, 105, 0.919);
                }

                // box-shadow: 0px 0px 6px 0px rgba(149, 149, 149, 0.6);
              }
            }
          }
        }
      }

      .addBtn {
        width: 100%;
        padding: 5px;

        .addBtn-container {
          width: 100%;
          height: 35px;
          line-height: 35px;
          text-align: center;
          border-radius: 50px;
          background-color: #ffbfb8;
          color: white;
          font-weight: 600;
        }
      }
    }
  }
}
</style>